/*
 * @Author: Hzh
 * @Date: 2021-05-18 16:16:35
 * @LastEditTime: 2021-05-18 16:53:55
 * @LastEditors: Hzh
 * @Description:
 */
export function permissionDirective(store) {
  const permission = permissionInserted(store);
  const install = function (Vue) {
    Vue.directive("permission", permission);
  };
  if (window.Vue) {
    window["permission"] = permission;
    Vue.use(install); // eslint-disable-line
  }
  permission.install = install;
  return permission;
}

function permissionInserted(store) {
  return {
    inserted(el, binding, vnode) {
      const { value } = binding;
      const isQiankun = window.__POWERED_BY_QIANKUN__;
      const roles = store.state.global && store.state.global.btnCodeList;
      const systemEnName =
        store.state.settings && store.state.settings.systemEnName;
      if (isQiankun) {
        if (!roles) {
          throw new Error(
            `检查一下是否有global这个模块，以及btnCodeList是否为空`
          );
        }
        if (!systemEnName) {
          throw new Error(
            `检查一下是否有settings这个模块，以及systemEnName是否为空,systemEnName就是packJson的name`
          );
        }

        if (value && value instanceof Array && value.length > 0) {
          const permissionRoles = value.map((item) => {
            item = `${systemEnName}.${item}`;
            return item;
          });

          const hasPermission = roles.some((role) => {
            return permissionRoles.includes(role);
          });

          if (!hasPermission) {
            el.parentNode && el.parentNode.removeChild(el);
          }
        } else {
          throw new Error(
            `使用方式： v-permission="['PageName.operation']",PageName就是当前页面的name，operarion就是接口对象名称`
          );
        }
      }
    },
  };
}

export function checkPermission(store,value) {
  const isQiankun = window.__POWERED_BY_QIANKUN__
  const roles = store.state.global && store.state.global.btnCodeList
  const systemEnName = store.state.settings && store.state.settings.systemEnName

  if (isQiankun) {
    if (!roles) {
      console.error(`检查一下是否有global这个模块，以及btnCodeList是否为空`)
      return false
    }

    if (!systemEnName) {
      console.error(`检查一下是否有settings这个模块，以及systemEnName是否为空,systemEnName就是packJson的name`)
      return false
    }

    if (value && value instanceof Array && value.length > 0) {
      const permissionRoles = value.map(item => {
        item = `${systemEnName}.${item}`
        return item
      })

      const hasPermission = roles.some(role => {
        return permissionRoles.includes(role)
      })

      if (!hasPermission) {
        return false
      }
      return true
    } else {
      console.error(`使用方式： v-permission="['PageName.operation']",PageName就是当前页面的name，operarion就是接口对象名称`)
      return false
    }
  } else {
    return true
  }
}
